package com.indsvr.controller;

import com.indsvr.XunleiApiApplication;
import com.indsvr.entity.response.IndSvrRoot;
import com.indsvr.utils.CompressDirUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

@Controller
public class PluginController {

    @Value("${indsvr.version}")
    private String version;


    @Value("${indsvr.jarfiles}")
    private String jarfiles;


    @ResponseBody
    @RequestMapping("/plugin")
    public void test(HttpServletResponse response) throws Exception {
        response.reset();
        response.setCharacterEncoding("UTF-8");
        response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("plugin.zip", "UTF-8"));
        ServletOutputStream outputStream = response.getOutputStream();
        CompressDirUtil.compressFileToZip(jarfiles+"/BOOT-INF/classes/static/chrome", outputStream);
        outputStream.flush();
        outputStream.close();
    }

    @ResponseBody
    @RequestMapping("/status")
    public IndSvrRoot status(HttpServletResponse response) throws Exception {
        return IndSvrRoot.ok("0");
    }

    //解压文件并修改版本号
    @Bean
    public void setVersion() throws IOException {

        String jarPath = XunleiApiApplication.class.getProtectionDomain().getCodeSource().getLocation().getPath();
        String replace = jarPath.replace("file:/", "").replace("!/BOOT-INF/classes!/", "");

        if (!replace.contains(".jar")) {
            return;
        }

        unzip(replace,jarfiles);

        File file = ResourceUtils.getFile(jarfiles+"/BOOT-INF/classes/static/chrome/manifest.json");

        StringBuilder json = new StringBuilder();
        // 2. 创建字符输入流
        try (FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr)) {
            String line;
            // 4. 逐行读取文件内容
            while ((line = br.readLine()) != null) {
                json.append(line);
            }
        } catch (IOException e) {
            // 处理异常
            e.printStackTrace();
        } // 5. 自动关闭流

        String jsonS = json.toString().replace("\"version\": \"65536\"", "\"version\": \""+version+"\"");

        FileOutputStream fileOutputStream = new FileOutputStream(file);
        fileOutputStream.write(jsonS.getBytes());
        fileOutputStream.flush();
        fileOutputStream.close();

    }



    public static void unzip(String zipFilePath, String destDir) throws IOException {
        byte[] buffer = new byte[1024];
        ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipFilePath));
        ZipEntry zipEntry = zipInputStream.getNextEntry();

        while (zipEntry != null) {
            String fileName = zipEntry.getName();
            String filePath = destDir + File.separator + fileName;

            // Create directories if not exists
            if (zipEntry.isDirectory()) {
                File dir = new File(filePath);
                dir.mkdirs();
            } else {
                // Extract file
                FileOutputStream fileOutputStream = new FileOutputStream(filePath);
                int length;
                while ((length = zipInputStream.read(buffer)) > 0) {
                    fileOutputStream.write(buffer, 0, length);
                }
                fileOutputStream.close();
            }

            zipEntry = zipInputStream.getNextEntry();
        }

        zipInputStream.closeEntry();
        zipInputStream.close();
    }

}
